import React, { PureComponent } from 'react';
import { message } from 'antd';
import { DATA_ENTRY, PrimaryC, TableC, AdvancedSearch } from '../../../../comps';
import config from '../../../../comps/business/searchAndSelect/enum';
import { connect } from 'dva';
@connect(({ nonstandarmaintenanceNewM }) => ({ nonstandarmaintenanceNewM }))
export default class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      searchObj: {},
      currentPage: 1,
      numInPage: 10,
      total: 0,
      isReset: false, //是否重置
      columns1: [
        { dataIndex: 'assetType', title: '资产类别', key: 'assetType', width: 150 },
        { dataIndex: 'tradingcode', title: '证券代码', key: 'tradingcode', width: 180 },
        { dataIndex: 'tradingname', title: '证券全称', key: 'tradingname', width: 180 },
        { dataIndex: 'parTotalValue', title: '初始份额面值', key: 'parTotalValue', width: 120 },
        { dataIndex: 'issueScale', title: '发行规模', key: 'issueScale', width: 120 },
        { dataIndex: 'startDate', title: '起息日', key: 'startDate', width: 120 },
        { dataIndex: 'endDate', title: '到期日', key: 'endDate', width: 120 },
        { dataIndex: 'fixedRate', title: '利率（%）', key: 'fixedRate', width: 100 },
        { dataIndex: 'interestBasis', title: '计息基础', key: 'interestBasis', width: 100 },
        { dataIndex: 'mainRatingStart', title: '融资人主体评级', key: 'mainRatingStart', width: 120 },
        { dataIndex: 'debtRatingStart', title: '资产评级', key: 'debtRatingStart', width: 100 },
        { dataIndex: 'userId', title: '创建人', key: 'userId', width: 120 },
      ],
      columns2: [
        { dataIndex: 'tradingcode', title: '证券代码', key: 'tradingcode', width: 180 },
        { dataIndex: 'tradingname', title: '证券全称', key: 'tradingname', width: 180 },
        { dataIndex: 'startDate', title: '起息日', key: 'startDate', width: 120 },
        { dataIndex: 'endDate', title: '到期日', key: 'endDate', width: 120 },
        { dataIndex: 'type', title: '票据类型', key: 'type', width: 100 },
        { dataIndex: 'num', title: '票据数量', key: 'num', width: 120 },
        { dataIndex: 'totalNum', title: '合计金额', key: 'totalNum', width: 120 },
        { dataIndex: 'rate', title: '贴现利率（%）', key: 'rate', width: 100 },
      ],
      columns: [],
      dataSource: [],
      isReset: false, // 是否点击重置
      sortedInfo: null, //排序对象
    };
  }
  componentDidMount() {
    this.props?.onRef && this.props?.onRef(this);
    this.getTableData();
  }

  // 遍历树形结构，找出value==keys的那条数据
  findKeys = (treeData, id, arr) => {
    treeData?.length &&
      treeData?.forEach((item) => {
        if (item.value == id) {
          arr.push(item.title);
        } else if (item && item.children && item.children.length > 0) {
          this.findKeys(item.children, id, arr);
        }
      });
    return arr;
  };
  // 获取表格数据
  getTableData = () => {
    const { currentPage, numInPage, searchObj, sortedInfo } = this.state;
    this.setState(
      {
        columns: undefined,
        dataSource: undefined,
      },
      () => {
        let obj = {};
        if (sortedInfo?.order) {
          (obj.columnKey = sortedInfo?.columnKey), (obj.order = sortedInfo?.order);
        }
        this.props.dispatch({
          type: this.props.activeKey == 1 ? 'nonstandarmaintenanceNewM/getAssetTableData' : 'nonstandarmaintenanceNewM/getInvestTableData',
          payload: {
            ...searchObj,
            currentPage: currentPage,
            numInPage: numInPage,
            ...obj,
          },
          callback: (type, data) => {
            if (type == 'success') {
              this.setState({
                columns: this.props.activeKey == 1 ? this.state.columns1 : this.state.columns2,
                dataSource: data.dataSource,
                total: data.pageInfo && data.pageInfo.total,
              });
            }
          },
        });
      },
    );
  };
  //表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    this.setState(
      {
        sortedInfo: sorter,
      },
      () => {
        if (isReset) {
          //判断是否点击了重置 点击页码不进行后台查询
          message.warning('查询条件已被重置，请重新查询。');
          return;
        }
        this.setState(
          {
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getTableData();
          },
        );
      },
    );
  };
  // 操作 type=add 新增，edit 编辑 view 查看
  handleFn = (record, type) => {
    if (type == 'add') {
      let addRecord = {
        baseInfo: {}, //基本信息
        reportInfo: {}, //监管报表信息
        files: [], //资产包
        zgtzptNonstandarCashFlows: [],
      };
      this.props.changePageStatus && this.props.changePageStatus(addRecord, type);
    } else if (type == 'edit' || type == 'view') {
      // 编辑
      this.props.dispatch({
        type: 'nonstandarmaintenanceNewM/getDataById',
        payload: {
          id: record.id,
        },
        callback: (types, res) => {
          if (types == 'success') {
            this.props.changePageStatus && this.props.changePageStatus(res, type);
          }
        },
      });
    }
  };
  // 删除
  del = (record) => {
    this.props.dispatch({
      type: 'nonstandarmaintenanceNewM/deleteById',
      payload: {
        id: record.id,
      },
      callback: (res) => {
        if (res == 'success') {
          this.getTableData();
        }
      },
    });
  };

  //修改columns的状态
  changeColumns = (columns) => {
    const {
      nonstandarmaintenanceNewM: { dictMapSelect },
    } = this.props;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};
    let data = columns;
    if (data && data.length) {
      if (data?.length && data[data?.length - 1].title != '操作') {
        data.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          fixed: 'right',
          width: 150,
          operates: [
            {
              title: '查看',
              onClick: (record, index) => {
                this.handleFn(record, 'view');
              },
            },
            {
              title: '编辑',
              onClick: (record, index) => {
                this.handleFn(record, 'edit');
              },
            },
            {
              title: '删除',
              onClick: (record, index) => {
                this.del(record);
              },
            },
          ],
        });
      }
      columns &&
        columns?.length &&
        columns.map((item) => {
          if (item.key == 'assetType' || item.key == 'tradingcode' || item.key == 'startDate' || item.key == 'endDate') {
            if (this.props.activeKey == 2 && item.key == 'assetType') return;
            item.sorter = true;
            item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
          }
        });
      if (this.props.activeKey == 1) {
        // 投资列表
        columns &&
          columns.length &&
          columns.forEach((item) => {
            if (item.dataIndex == 'assetType') {
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = dictMapSelect['ASSETS_ASSET_TYPE']?.length && dictMapSelect['ASSETS_ASSET_TYPE'].find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
            if (item.dataIndex == 'parTotalValue' || item.dataIndex == 'issueScale') {
              item.type = 'money';
            }
            //利率（%）
            if (item.dataIndex == 'fixedRate') {
              item.type = 'rate';
            }
            //计息基础
            if (item.dataIndex == 'interestBasis') {
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = dictMapSelect['ASSETS_INTEREST_BASIS']?.length && dictMapSelect['ASSETS_INTEREST_BASIS'].find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
            //融资人主体评级
            if (item.dataIndex == 'mainRatingStart') {
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = dictMapSelect['ASSETS_MAIN_RATING_START']?.length && dictMapSelect['ASSETS_MAIN_RATING_START'].find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
            //资产评级
            if (item.dataIndex == 'debtRatingStart') {
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = dictMapSelect['ASSETS_MAIN_RATING_START']?.length && dictMapSelect['ASSETS_MAIN_RATING_START'].find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
          });
      }
      if (this.props.activeKey == 2) {
        // 投资列表
        columns &&
          columns.length &&
          columns.forEach((item) => {
            if (item.dataIndex == 'type') {
              // 类型 前端翻译
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = dictMapSelect['INVEST_TYPE']?.length && dictMapSelect['INVEST_TYPE'].find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
            if (item.dataIndex == 'num') {
              item.type = 'number';
            }
            if (item.dataIndex == 'totalNum') {
              item.type = 'money';
            }
            if (item.dataIndex == 'rate') {
              item.type = 'rate';
            }
          });
      }
    }
    return data;
  };

  render() {
    const { columns, dataSource, total, currentPage, numInPage } = this.state;
    const newColumns = this.changeColumns(columns);
    const { listRefresh } = this.props.nonstandarmaintenanceNewM;
    if (listRefresh) {
      this.props
        .dispatch({
          type: 'nonstandarmaintenanceNewM/listRefresh',
          payload: {
            listRefresh: false,
          },
        })
        .then(() => {
          this.getTableData();
        });
    }
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['codeId', 'code'],
          title: '证券代码',
          type: DATA_ENTRY.SEARCHANDSELECTC,
          codeType: this.props.activeKey == 1 ? config.fbzc : config.fbtz,
        },
        {
          dataIndex: ['startDateStart', 'startDateEnd'],
          title: '起息日区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [null, null],
          onRef: (ref) => this.setState({ RANGEDATE: ref }),
          disableFuture: false,
          allowClear: true,
        },
        {
          dataIndex: ['endDateStart', 'endDateEnd'],
          title: '到期日区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [null, null],
          onRef: (ref) => this.setState({ RANGEDATEEnd: ref }),
          disableFuture: false,
          allowClear: true,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        if (Object.keys(e).length == 1 && Object.keys(e)[0] == 'codeId') {
          //产品名称精准查询时清空其他查询条件
          this.state.RANGEDATE.reset();
          this.state.RANGEDATEEnd.reset();
        }
        let tempQuery = {};
        for (let k in e) {
          if (k == 'startDateStart' || k == 'startDateEnd' || k == 'endDateStart' || k == 'endDateEnd') {
            tempQuery[k] = e[k].format('YYYY-MM-DD');
          } else {
            tempQuery[k] = e[k];
          }
        }
        this.setState(
          {
            currentPage: 1,
            numInPage: 10,
            searchObj: tempQuery,
            isReset: false,
          },
          () => {
            this.getTableData();
          },
        );
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          sortedInfo: null, //排序对象
          isReset: true,
        });
      },
    };
    return (
      <div>
        <div style={{ margin: '10px 0 10px 0' }}>
          <AdvancedSearch {...searchProps}></AdvancedSearch>
        </div>
        <div style={{ marginTop: '10px' }}>
          <PrimaryC title='新增' style={{ marginBottom: '10px' }} onClick={() => this.handleFn({}, 'add')} />
        </div>
        <TableC
          columns={newColumns}
          dataSource={dataSource}
          current={currentPage}
          total={total}
          pageSize={numInPage}
          rowKey='id'
          selfScrollY={true}
          scroll={{ x: 'max-content' }}
          onChange={this.handleTableChange}
        />
      </div>
    );
  }
}
